简体   繁体   English

JavaScript:函数未修改实际数组

[英]JavaScript: Function not modifying the actual array

I have arrays like this: 我有这样的数组:

[ 'markdown', [ 'para', '\'example\'' ] ]

And I have a function that finds recursively the strings inside those arrays: 我有一个函数可以递归地找到这些数组中的字符串:

function traverse(tree, callback) {
  for (var i = 0; i < tree.length; ++i) {
    if (_.isArray(tree[i]) || _.isObject(tree[i])) {
      traverse(tree[i], callback)
    } else {
      callback(tree[i])
    }
  }
}

The problem is, when I perform tasks like replace what's being replaced isn't the actual array but just copies of its nodes. 问题是,当我执行诸如replace之类的任务时,被替换的不是实际的数组,而只是其节点的副本。 Example: 例:

function replaceQuotes(tree, callback) {

  traverse(tree, function(node) {
    node = node.replace(/'/g, '"')
    console.log(node)
    // outputs: "example"
  })

  callback(null, tree)
}

function showResult(err, tree) {
   console.log(tree)
   // outputs [ 'markdown', [ 'para', '\'example\'' ] ]
}

How can I do it so I can I modify the actual arrays with the transverse function? 我该怎么做,以便可以使用transverse函数修改实际数组?

(By the way, I'm using the Async Node.js module.) (顺便说一句,我正在使用异步 Node.js模块。)

Strings are passed by value - this is why your code behaves the way it does. 字符串按值传递-这就是代码执行行为的原因。 A good solution is to make your callback return the new value and then modify your traverse slightly: 一个好的解决方案是使您的回调返回新值,然后稍微修改遍历:

function tranverse(tree, callback) {
  for (var i = 0; i < tree.length; ++i) {
    if (_.isArray(tree[i]) || _.isObject(tree[i])) {
      tranverse(tree[i], callback)
    } else {
      tree[i] = callback(tree[i]) // changed part
    }
  }
}

You would then use it like this: 然后,您可以像这样使用它:

function replaceQuotes(tree, callback) {

  tranverse(tree, function(node) {
    return node.replace(/'/g, '"')
  })

  console.log(tree)
  // outputs [ 'markdown', [ 'para', '\'example\'' ] ]

  callback(null, tree)
}

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

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