gpt4 book ai didi

javascript - 循环对象并添加类型

转载 作者:行者123 更新时间:2023-11-28 18:31:34 25 4
gpt4 key购买 nike

function arrayToList(array) {
var list = null;
for (var i = 0; i < array.length ; i++)
list = {value: array[i], rest: list};
return list;

}

console.log(arrayToList([10,20]));

为什么当我 console.log 这个数组时,我获取的是 value : 20rest: object,而不是 值:10其余:null。这让我很困惑,因为传入的数组的第一个元素是 10,而我将从 i = 0 开始。任何见解都会有帮助。谢谢。

最佳答案

这是因为您要返回最后一个设置为 list 的对象。要返回链表中的第一个,请在循环之前保留对其的引用,然后返回该引用。

虽然你的链接列表与数组相反。不确定这是否是您想要的。

如果您想列出镜像数组并转发链接,请执行以下操作:

function arrayToList(array) {
var first = {value: array[0], rest: null};
var prev = first;
for (var i = 1; i < array.length ; i++)
prev.rest = prev = {value: array[i], rest: null};

return first;
}

console.log(arrayToList([10,20]));

<小时/>

假设我们没有循环,只是内联整个事情。这就是它的样子。我也将按照数组 [10, 20, 30] 的方式进行操作。

function arrayToList(array) {
// Here `first` and `prev` reference the same object
var first = {value: array[0], rest: null};
var prev = first;

// first = {value: 10, rest: null};
// prev = {value: 10, rest: null};

// Then we assign a new object to `prev.rest` as well as `prev`.
// Because the `prev` and `first` variables reference the same object,
// the mutation of `prev.rest` is also seen from `first.rest`.

// First iteration
prev.rest = prev = {value: array[1], rest: null};

// now...
// first = {value: 10, rest: (reference to object with value: 20)};
// prev = {value: 20, rest: null};

// So it first changed `prev.rest` (and therefore `first.rest`) to point to
// the new object, but then it also updated `prev` to the same, new object.

// Take note that though we assigned the new object to `prev.rest`, after
// the assignment, `prev.rest` is actually `null`, because the `prev.rest`
// that we assigned to was the `.rest` of the *previous* `prev`, which was
// immediately updated to see the *new* object.

// Second iteration
prev.rest = prev = {value: array[2], rest: null};

// now...
// first = {value: 10, rest: (reference to object with value: 20)};
// prev = {value: 30, rest: null};

// So now when we changed `prev.rest`, it had no impact on `first` because
// `prev` and `first` are referencing different objects. So `prev` sees the
// new object, but `first` does not.

return first;
}

关于javascript - 循环对象并添加类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com