user5607806
user5607806

Reputation:

Assigned variable follows the changes of array unexpectedly

I assign the new variable to an array. after modifying the array the assigned variable follows the changes of array unexpectedly!

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = orders;

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

Upvotes: 1

Views: 50

Answers (4)

coderman401
coderman401

Reputation: 582

let answer = orders.slice(0) will make a shallow copy of your array object. in my opinion, to copy your array object the solution is:

let answer = copy(orders);

// copy function
function copy(object) {
    var output, value, key;
    output = Array.isArray(object) ? [] : {};
    for (key in object) {
        value = object[key];
        output[key] = (typeof value === "object") ? copy(value) : value;
    }
    return output;
}

Upvotes: 1

uiTeam324
uiTeam324

Reputation: 1245

This will solve your issue.

let answer = [...orders];

Upvotes: 0

Andy Mardell
Andy Mardell

Reputation: 1191

You're mutating the existing array. Clone it by doing the following:

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = [...orders];

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

Alternatively, you can use let answer = orders.slice(0) if you're not using es6

Upvotes: 0

kooskoos
kooskoos

Reputation: 4859

let answer = orders;

You are copying reference of orders to answer as it is an array.

It's like giving another name to the same array(block of memory).

This should solve your problem

Change let answer = orders; to let answer = [...orders];

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = [...orders];

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

Upvotes: 2

Related Questions