从另一个数组推送新元素,不起作用 [英] push new element from another array, not working

查看:117
本文介绍了从另一个数组推送新元素,不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面编写的代码有问题
我不确定这有什么问题,有人可以提示我

i''m having problems with the code i made below
i''m not sure whats wrong with it, could someone hint me

var myarr = ['tpc001:10','tpc003:5','tpc000:4','tpc001:7','tpc003:4','tpc008:1'];
var sumarr =[];  // i create an empty array
myarr.sort();    // sorting myarr

sumarr.push(myarr[1]); // add first element of myarr to sumarr.


alert(sumarr[1]);   // error undefinied, but i just pushed a string value to it ??

推荐答案

好的,我会给您一个提示.索引从javascript中的零(0)开始.因此,如果您的示例中有一个像sumarr这样的空数组,然后将一个元素推入该数组(LIFO方式),则该数组中现在有多少个元素?
如果数组中有m个元素,并且想得到第m th 个元素,且<0 m< = n该元素的索引将为m-1.

干杯!

—MRB
OK, I''ll give you a hint. Indices start from zero (0) in javascript. So if you have an empty array like sumarr in your example and then push one element onto that array (LIFO fashion) how many elements are now in the array?
If there are m elements in an array and one wants to get at the mth element with 0 < m <= n the index of that element will be m-1.

Cheers!

—MRB
var myarr = ['tpc001:10','tpc003:5','tpc000:4','tpc001:7','tpc003:4','tpc008:1'];
var sumarr =[];  // i create an empty array
myarr.sort();    // sorting myarr

sumarr.push(myarr[1]); // add the second element of myarr to sumarr.


alert(sumarr[0]);   // Since there is only one element in sumarr that's all you will get here


这篇关于从另一个数组推送新元素,不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆