var Config = {
Windows: ['apple','mangi','lemon']
}
我有一个条件,基于此我想将香蕉值推送到我的数组中。
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();
}
它不这样做...当我在其他函数中使用 Config.Windows 时,根本没有 banana
值...
for each(var item in Config.Windows.reverse()) {
Ti.API.info(item);
//This does not print 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'] }
关于javascript - 将数组值推送到第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358130/