简体   繁体   中英

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. 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?

(By the way, I'm using the Async Node.js module.)

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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