JavaScript 将数组中的一项移到最前面 [英] JavaScript move an item of an array to the front
本文介绍了JavaScript 将数组中的一项移到最前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查一个数组是否包含"role"
.如果是这样,我想将 "role"
移动到数组的前面.
I want to check if an array contains "role"
. If it does, I want to move the "role"
to the front of the array.
var data= ["email","role","type","name"];
if ("role" in data) data.remove(data.indexOf("role")); data.unshift("role")
data;
这里,我得到了结果:
["role", "email", "role", "type", "name"]
我该如何解决这个问题?
How can I fix this?
推荐答案
您可以对数组进行排序并指定值 "role"
在所有其他值之前,并且所有其他值都相等:
You can sort the array and specify that the value "role"
comes before all other values, and that all other values are equal:
var first = "role";
data.sort(function(x,y){ return x == first ? -1 : y == first ? 1 : 0; });
演示:http://jsfiddle.net/Guffa/7ST24/
这篇关于JavaScript 将数组中的一项移到最前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文