开发者

difference between push and normal array assignment in javascript

开发者 https://www.devze.com 2023-03-21 12:28 出处:网络
开发者_如何学CI\'m usingflot api to draw charts. Look at this chart type HERE. In that example they\'ve used values like,

开发者_如何学CI'm using flot api to draw charts. Look at this chart type HERE.

In that example they've used values like,

var sin = [], cos = [];
  for (var i = 0; i < 14; i += 0.5) {
        sin.push([i, Math.sin(i)]);
        cos.push([i, Math.cos(i)]);
  }

Now the chart was drawn "curved" lines, when i replaced the

sin.push([i, Math.sin(i)]);
cos.push([i, Math.cos(i)]);

with,

sin[i]=[i, Math.sin(i)];
cos[i]=[i, Math.cos(i)];

Then the chart gets drawn using straight lines. I've two questions now.

1) What is the difference between the two types of array assignments?

2) Is this because of difference in array assignments or the API behaviour?

any help greatly appreciated! Thanks.

Edit: Set i to increment by 1 and set different values using push method or default assignment, you'll get the same result.


The i is not Integer. You can use only int in array index.

1) What is the difference between the two types of array assignments? A) None, except the push places next int for index.

2) Is this because of difference in array assignments or the API behaviour? A) Yes with your way the array is invalid, because the 1.5 value for a key is parsed as a string and api can not read the array as it expect.

Try using apis way or using different values for for statement.


I think there's a problem with i increment. It is clear that on every iteration i is increased by 0.5, not 1. Look:

for (var i = 0; i < 14; i += 0.5) 

So sin[i]=... won't work properly. But sin.push(...) will work.


Array indexes can't be fractions and are always strings, so the number 1.5 is being converted to a string '1.5' and the sequence will be '0', '0.5', '1', '1.5' and so on. But using push, all indexes will be integer strings, so will be 0, 1, 2, etc.

No doubt an integer based loop is being used to read the values from the array, so it is skipping the .5 ones (i.e. every second element) and giving jagged edges.


Generally this would work, but in this case you're incrementing i by 0.5 which results in i being a float-value.

Look at the output of both variants:

// push
// cos
[[0, 1], 
 [0.5, 0.8775825618903728], 
 [1, 0.5403023058681398], 
 [1.5, 0.0707372016677029], 
 [2, -0.4161468365471424], 
 [2.5, -0.8011436155469337], ...]

// sin
[[0, 0], 
 [0.5, 0.479425538604203], 
 [1, 0.8414709848078965], 
 [1.5, 0.9974949866040544], 
 [2, 0.9092974268256817], 
 [2.5, 0.5984721441039564], ...]

// array-index
// cos
[[0, 1], 
 [1, 0.5403023058681398], 
 [2, -0.4161468365471424], 
 [3, -0.9899924966004454], 
 [4, -0.6536436208636119], ...]

// sin
[[0, 0], 
 [1, 0.8414709848078965], 
 [2, 0.9092974268256817], 
 [3, 0.1411200080598672], 
 [4, -0.7568024953079282], ...]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号