在下面的代码片段中,最后一个控制台日志显示(节点值)空字典,你能告诉我原因吗?
function add(n1, n2) {
const sum = []
let carry = 0
for (let i = 0; i < n1.length || i < n2.length || carry; i++) {
const added = (n1[i] || 0) + (n2[i] || 0) + carry
sum[i] = added % 10
carry = added > 9 //floor(added / 10)
}
return sum
}
function times256(n1) {
for (let i = 8; i; i--) n1 = add(n1, n1)
return n1
}
function toString(buffer) {
const isNegative = buffer[0] & 128 //check if high bit is set
if (isNegative) { //convert to positive, using 2's complement
buffer = buffer.map(b => ~b) //invert all bits
let i = buffer.length - 1
while (buffer[i] === 255) { //add 1 to the number, carrying if necessary
buffer[i] = 0
i--
}
buffer[i]++
}
const result = buffer.reduce((sum, b) =>
add(
times256(sum), //multiply sum by 256
String(b).split('').map(Number).reverse() //then add b
),
[]
)
const stringResult = result.reverse().join('')
if (isNegative) return '-' + stringResult
else return stringResult
}
答案 0 :(得分:1)
因为您使用list1[each]
创建了一个基本上是1 ... 3的新属性,它是一个对象。此对象已分配给节点。
var abc = function(t1, key) {
t1[key] = {};
return t1;
}
var node = {},
list1 = [1, 2, 3],
each;
for (each in list1) {
console.log(node);
console.log(abc(node, list1[each])[list1[each]]);
console.log(list1[each]);
node = abc(node, list1[each])[list1[each]];
}
console.log(node);
&#13;
要获取具有所需属性的对象,可以使用另一个变量并将新对象移动到给定对象内。
var abc = function(t1, key) {
t1[key] = {};
console.log(t1);
return t1[key]; // return new object
}
var node = {},
temp = node,
list1 = [1, 2, 3],
each;
for (each in list1) {
temp = abc(temp, list1[each]); // assign just the new object
}
console.log(node);
&#13;
答案 1 :(得分:1)
这是因为您在每次循环迭代中都覆盖了节点变量。尝试制作备份参考:
node = {};
nodebackup = node;
list1=[1,2,3];
for(each in list1){
console.log(nodebackup);
var abc = function(t1, key){
t1[key] = {};
return t1;
}
node=abc(node, list1[each])[list1[each]]
}
console.log(nodebackup)