繁体   English   中英

为什么我的函数不能更改对象值?

[英]Why won't my function change object value?

为什么add()函数对LIST没有影响? 我想创建的是这样的: 在此处输入图片说明

function arrayToList(array){
    LIST = {};
    function add(list, index){
        if(index < array.length){
            list = {value:array[index], rest : null};
            add(list.rest, index+1);
        }
    }
    add(LIST,0);
    return LIST;
}

您的代码的编写就像JavaScript是一种传递引用的语言一样。 它不是。

具体来说,在add()函数内部,您的代码被编写为好像对参数list进行赋值会对作为参数传递给函数的内容产生影响。 它不会。 也就是说,此语句:

        list = {value:array[index], rest : null};

将修改参数的值,但不会影响全局变量LIST

您可以通过多种方式重新设计代码。 这是一种方法:

function arrayToList(array){
    function add(index){
        var entry = null;
        if (index < array.length) {
            entry = { value: array[index], rest: add(index + 1) };
        }
        return entry;
    }
    return add(0);
}

首先,您需要在LIST前面拍一个var ,这样就不会创建全局变量。

function arrayToList(array) {
  var LIST = {};
  ...
}

接下来,问题是当您传递list.rest ,您没有传递对该属性的引用。 您只是传递null的值。 相反,您可能想尝试在最后创建一个节点,但将值设置为null

function arrayToList(array) {
  var LIST = {};
  function add(list, index) {
    if (index < array.length) {
      list.value = array[index];
      list.rest = {};
      add(list.rest, index + 1);
    } else {
      list.rest = list.value = null;
    }
  }
  add(LIST, 0);
  return LIST;
}

编辑:或者,如果要确保end为null ,则可以在add函数内部执行简单检查。

function add(list, index) {
  if (index < array.length) {
    list.value = array[index];
    if (index + 1 < array.length) {
      list.rest = {};
      add(list.rest, index + 1);
    } else {
      list.rest = null;
    }
  }
}

暂无
暂无

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

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