javascript 将数组值推送到第一个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6358130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pushing Array value to first Index
提问by John Cooper
var Config = {
Windows: ['apple','mangi','lemon']
}
I have a condition and based on that i want to Push the banana value in my Array.
我有一个条件,基于这个条件,我想在我的数组中推送香蕉值。
If(Condition Passed) {
Config.Windows.unshift('banana');
Windows: ['banana','apple','mangi','lemon']
Config.Windows.reverse();
// The way the Array elements are now reversed and First banana is accessed.
} else {
Config.Windows.reverse();
}
It does not do it... when i use the Config.Windows in my other function there is no banana
Value... at all
它不这样做......当我在我的其他函数中使用 Config.Windows 时,根本没有任何banana
价值......
for each(var item in Config.Windows.reverse()) {
Ti.API.info(item);
//This does not print banana
采纳答案by NT3RP
There are many ways in which you can push the value to the front of the array. Immediately, I can think of two ways:
有多种方法可以将值推送到数组的前面。马上,我可以想到两种方法:
Create a new array, and replace the old one
if (condition) { Config.Windows = ['banana'].join(Config.Windows) Config.Windows.reverse(); } else { Config.Windows.reverse(); }
Based on what you've said, it would make more sense to always reverse the array, then push your value:
//initial array: ['apple','mangi','lemon'] Config.Windows.reverse(); //['lemon','mangi','apple'] if (condition) { //this will get the same result as your code Config.Windows.push("banana"); //['lemon','mangi','apple', 'banana'] }
创建一个新数组,并替换旧数组
if (condition) { Config.Windows = ['banana'].join(Config.Windows) Config.Windows.reverse(); } else { Config.Windows.reverse(); }
根据你所说的,总是反转数组会更有意义,然后推动你的价值:
//initial array: ['apple','mangi','lemon'] Config.Windows.reverse(); //['lemon','mangi','apple'] if (condition) { //this will get the same result as your code Config.Windows.push("banana"); //['lemon','mangi','apple', 'banana'] }
回答by Jon
"The unshift is not supported by IE so if that's your browser it explains why it's not working. "
“IE 不支持 unshift,所以如果那是你的浏览器,它会解释为什么它不起作用。”
http://msdn.microsoft.com/en-us/library/ie/ezk94dwt(v=vs.94).aspx
http://msdn.microsoft.com/en-us/library/ie/ezk94dwt(v=vs.94).aspx