JavaScript的移动数组的一个项目前 [英] JavaScript move an item of an array to the front

查看:91
本文介绍了JavaScript的移动数组的一个项目前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查如果一个数组包含角色。如果是这样,我想移动角色到阵列的前端。

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;

在这里,我得到的结果:

Here, I got the result:

[角色,电子邮件,角色,型,名]

我该如何解决这个问题?

How can I fix this?

推荐答案

您可以在阵列进行排序,并指定该值角色来自所有其他值之前,和所有其他的值相等:

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屋!

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