我正在尝试更改属于对象数组一部分的对象的属性值,并在控制台中收到以下消息:
Uncaught TypeError: Cannot set property 'editable' of undefined
将此属性的值打印到控制台可以工作,但更改它则不行。以下是我的 jsfiddle。
如何更改上述 jsfiddle 中对象数组一部分的对象的值?
//data file
var data = [
{editable:true,greeting:'hello'},
{editable:true,greeting:'bye'},
{editable:true,greeting:'good morning'}
];
//updating data
var readWrite = function (text, label, value){
for (i=0;i<=text.length;i++){
if (label=='editable'){
if (value==true){
//changing the value of the editable property DOES NOT WORK
text[i].editable=true;
}
else {
text[i].editable=false;
}
}
}
//printing data after changing the values of its properties
console.log(data);
}
$(document).ready(function(){
//printing data to the console
console.log(data);
//updating data and printing it to the console - DOES NOT WORK - what am I missing?
readWrite(data, 'editable', true);
})
最佳答案
你的循环不对,改成<=
至<
:
for (i=0;i<text.length;i++){
使用<=
正在出界,使得 text[i]
不明确的。它迭代所有对象,然后尝试再次迭代一个不存在的对象。
关于javascript - 无法设置未定义的属性 'editable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871931/