有人可以确认这个理论是否正确吗? - JavaScript 和数组
我正在学习 javascript,而且真的才刚刚开始 - 我正在 Firefox 中使用 Firebug 扩展来尝试一些东西。
我已经设置了 2 个 var(iables),第二个使用第一个变量中的值:
var multipleValues = [10,20,30,40,50] ;
var reverse = multipleValues.reverse();`
现在我想通过 if 语句从该数组中提取数据并创建一个警报,如下所示:
if (multipleValues [1] == 20) {
alert("Value is there.");
}
else {
alert("Value is not there");
}
现在这是我的问题 - 为什么当我像这样运行代码,它给了我“else”选项,但是当我注释掉 varverse
时,它显示为正确的?
我想因为我在开始时声明了变量,所以我可以稍后访问它,但是使用反向选项似乎会取消它?我是否误解了这个理论?
干杯
I am learning javascript and really just started - I am using the Firebug Extension in Firefox to try out a few things.
I have set up 2 var(iables) and the 2nd one uses values from the first one:
var multipleValues = [10,20,30,40,50] ;
var reverse = multipleValues.reverse();`
Now I want to pull data from that array via an if statement and create an alert like so:
if (multipleValues [1] == 20) {
alert("Value is there.");
}
else {
alert("Value is not there");
}
Now here is my question - How come when I run the code like this it gives me the "else" option, but when I comment out the var reverse
it comes up as correct?
I thought because I had declared the variable at the start I can access it later on, however using the reverse option seems to be canceling it out?? Am I misunderstanding the theory??
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
reverse
方法修改数组到位(同时还返回数组)。尝试这样的事情:The
reverse
method modifies the array in place (while also returning the array). Try something like this instead:Array.reverse() 具有破坏性,会更改原始数组。它还返回对数组的引用,因此两个对象应该彼此相等。
Array.reverse() is destructive and changes the original array. It also returns a reference to the array so the two objects should be equal to each other.
reverse()
就地反转数组。因此,它不会保留原始数组不变,而是将其反转。它还返回反转数组的值,因此
multipleValues
和reverse
都设置为反转值。JavaScript 可能会不一致。一些本机方法不会修改调用者,而是返回值(例如,
String.prototype.split
)。某些本机方法仅修改调用者,并且不返回相关值(Array.prototype.splice
就是一个示例)。一些本机方法(例如 Array.prototype.reverse)可以同时执行这两种操作。了解哪个功能的一种可靠方法是阅读文档;我推荐 Mozilla 开发者网络,它描述了
reverse( )
如下:reverse()
reverses the array in place.So, rather than leaving the original array unmodified, it reverses it. It also returns the value of the reversed array, so both
multipleValues
andreverse
are set to the reversed value.JavaScript can be inconsistent. Some native methods do not modify the caller, and instead return the value (Like, say,
String.prototype.split
). Some native methods only modify the caller and don't return a relevant value (Array.prototype.splice
is an example). Some native methods, like this one,Array.prototype.reverse
, do both.One reliable way to know which does what is to read documentation; I recommend Mozilla Developer Network, which describes
reverse()
as such: