QQ群招募中:646258285(招募中,没几个人说话),
需要交流的朋友可以直接加我微信( DntBeliv )或QQ( 1121864253 )
js获取对象,数组所有属性键值(key)和对应值(value)的方法
方法一[实用]====
let tempArr= [1,2,3,4,5,1,2];
if (tempArr.length > 1) {
let rep = [];
tempArr.forEach((item, index) => {
if (tempArr.indexOf(item) !== index) { // 匹配数组元素第一个item位置和当前循环的index
let obj = {};
obj.key = (tempArr.indexOf(item) + 1) + '|' + (index + 1); // 用'|'分隔两个重复项的下标
obj.value = item;
rep.push(obj);
}
});
console.log(rep);
}
方法二=====
var person = [
{ fname: "John", lname: "DD", age: 25},
{ fname: "Mike", lname: "MM", age: 23}
];
for (var i = 0; i < person.length; i++) {
for (x in person[i]) {
console.log(x + "=" + person[i][x]);
}
}
方法三=====
< script >
var values = function (object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
}
//写成标准的方法(数组是object的一种):
function getObjectKeys(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
}
function getObjectValues(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
}
//测试
var slideArray = [
{ "imgsrc1": "a.jpg"},
{ "imgsrc2": "b.jpg"},
{ "imgsrc3": "c.jpg"},
{ "imgsrc4": "d.jpg"},
{ "imgsrc5": "e.jpg"}
];
console.log(getObjectKeys(slideArray))
console.log(getObjectValues(slideArray)) < /script>