Reputation: 55283
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.)
Upvotes: 0
Views: 65
Reputation: 5534
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)
}
Upvotes: 2