为什么函数中的 array[i].key (where key === "surname") 不起作用,同时 array[i].surname 完美地工作?
let objects = [
{ name: 'Jack', surname: 'Jackson' },
{ name: 'Ivar', surname: 'Bjornsson' },
{ name: 'John', surname: 'Mickelson' }
];
function sort (array, key) {
for (let i = 0; i < array.length; i++) {
console.log(array[i].key)// Somehow the "key", which is equal to "surname" doesn't work;
// here will be undefined;
console.log(array[i].surname)//But here writing 'surname' directly works fine;
// the correct answer will be there;
console.log(key)// However, key === surname
}
}
sort(objects, 'surname');
您必须使用方括号访问该属性:
let objects = [
{ name: 'Jack', surname: 'Jackson' },
{ name: 'Ivar', surname: 'Bjornsson' },
{ name: 'John', surname: 'Mickelson' }
];
function sort (array, key) {
for (let i = 0; i < array.length; i++) {
console.log(array[i][key])// Somehow the "key", which is equal to "surname" doesn't work;
// here will be undefined;
console.log(array[i].surname)//But here writing 'surname' directly works fine;
// the correct answer will be there;
console.log(key)// However, key === surname
}
}
sort(objects, 'surname');
这个
array[i].key
相当于
array[i]['key']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句