0

What I'm trying to achieve is:

[1,2,3].power(2) === [1,4,9];

So far I did:

Array.prototype.power = function(value) {
    for (var i = 1; i < this.length; i++) {
        this[i] = Math.pow(this[i], value);
    }
}

but for some reason it return false and the array looks like:

[1, 4, 9, power: function...]

What I'm doing wrong here?

Ayeye Brazo
  • 3,316
  • 7
  • 34
  • 67

2 Answers2

0

You need to return the array:

Array.prototype.power = function(value) {
    for (var i = 0; i < this.length; i++) {
        this[i] = Math.pow(this[i], value);
    }
    return this;
}

var powers = [1,2,3].power(2); // [1, 4, 9]

Going into more depth now, you may see the power method listed as part of the Array when looking at the Array. This is one of the problems with prototyping the Array.

This doesn't mean that Array prototyping shouldn't be done. But understanding that, as an Array, it will still act like an Array so long as you used the Array methods in order to query/iterate it.

For example, taking the code example above, I can still get the correct length of the array:

powers.length; // 3

powers.toString() // 1,4,9

And if I iterate over it with index numbers, I can get an accurate reading:

for(var i = 0; i < powers.length; i++){

  console.log(powers[i]);

}

// 1
// 4
// 9

Quite simply: [1, 4, 9] are definitely the Array elements that are returned when using the power method above.

Community
  • 1
  • 1
shennan
  • 10,798
  • 5
  • 44
  • 79
  • you cannot compare arrays in the way that you're trying to compare them. Strict operators don't compare arrays. The result of `[1, 4, 9] == [1, 4, 9]` is also `false`. – shennan Apr 10 '15 at 15:59
  • IMO, this is a classic problem with prototyping the Array. It's okay to do it, but you need to have faith that, as an Array, it only has a length of `3`, and that if you iterate it properly, you will only get the intended values. – shennan Apr 10 '15 at 16:07
  • Can you please show an example? It is only 3 hours I'm fighting with it... Thanks – Ayeye Brazo Apr 10 '15 at 16:10
0

As mentioned already you can't just directly compare arrays. You can however write a simple method to see if there values match:

var arr = [1, 2, 3];
var arr2 = [1, 4, 9];

Array.prototype.power = function(value) {
    for (var i = 0; i < this.length; i++) {
        this[i] = Math.pow(this[i], value);
    }
    return this;
}

Array.prototype.compare = function(value) {   
    if (this.length !== value.length) {
         return false   
    }

    for (var i = 0; i < this.length; i++) {
        if (this[i] !== value[i]) {
         return false;   
        }
    }

    return true;
}

var convertedArray = [1, 2, 3].power(2);
var isEqual = convertedArray.compare(arr2);

Note: This assumes that the arrays will be the same length. You could add your own error handling for when they are not.

https://jsfiddle.net/g8mvne9r/5/

Mark Quinn
  • 46
  • 2