简体   繁体   English

不使用点表示法或括号表示法更新数组对象

[英]Array objects are not updated using dot notation or brackets notation

I would like to copy the size property of every object in dataArr to the corespondent size property of objects in testArr.我想将 dataArr 中每个对象的大小属性复制到 testArr 中对象的对应大小属性。 I have problem to understand (and I'm surprised) why it is not working.我有问题要理解(我很惊讶)为什么它不起作用。

CODE:代码:

 var testArr = [ {one : '1'}, {two : '2'}, {three : '3'} ]; var dataArr = [ {number : '0', size : '111'}, {number : '1', size : '222'}, {number : '2', size : '333'} ]; dataArr.forEach(function(item, index) { if (testArr[item.number] = item.number) { console.log('testArr[item.number] - ' + testArr[item.number]); // correct console.log('item.size - ' + item.size); // correct testArr[item.number].size = item.size; // not working testArr[item.number]['size'] = item.size; // not working either // WTF?! } }); console.log(testArr);

So why my testArr is not properly updated?那么为什么我的 testArr 没有正确更新?

testArr[item.number] is an object like {one: '1'} , but item.number is a string. testArr[item.number]是一个类似于{one: '1'}的对象,但item.number是一个字符串。 So they will never be equal, and the if test always fails.所以它们永远不会相等,并且if测试总是失败。

But the reason you're getting into the if block is because you used = rather than == , so you're assigning instead of comparing.但是您进入if块的原因是因为您使用了=而不是== ,所以您正在分配而不是比较。

You need to search testArr for the element whose value is the same as item.number .您需要在testArr中搜索其值与item.number相同的item.number

 var testArr = [ {one : '1'}, {two : '2'}, {three : '3'} ]; var dataArr = [ {number : '0', size : '111'}, {number : '1', size : '222'}, {number : '2', size : '333'} ]; dataArr.forEach(function(item) { var obj = testArr.find(obj => Object.values(obj)[0] == item.number); if (obj) { obj.size = item.size; } }); console.log(testArr);

In general, an array of objects that each have a different key is usually poor design, because you can't access the property easily.通常,每个具有不同键的对象数组通常是糟糕的设计,因为您无法轻松访问该属性。

Like others have said.就像其他人所说的那样。 You have 2 errors in this line:您在这一行中有 2 个错误:

if (testArr[item.number] = item.number)
  1. You are using the assignment operator = instead of equality operator == , and you should really use the type safe equality operator === to prevent erroneous type comparisons such as 0 == false returning true .您正在使用赋值运算符=而不是相等运算符== ,并且您应该真正使用类型安全的相等运算符===来防止错误的类型比较,例如0 == false返回true
  2. Even if you were using the correct operator, testArr contains objects, but you are comparing the object to a string item.number which doesn't make sense and will return false.即使您使用了正确的运算符, testArr包含对象,但您正在将对象与字符串item.number进行比较,该字符串没有意义并且将返回 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM