怎么把数组中的某一项移动到第一项

这个我暂时还没有更好的方法,目前我的想法是,找到要删除的项的索引,取到这一项,然后删除这一项,最后再数组最前方添加这一项

  • for 循环,得到index
  • 复制obj删除第index项,使用splice方法
  • 将复制的obj,放到数组最前方,使用unshift方法。
这是我本地写的测试:
var lastLoginTenantId = 3; var dataset = [{"tenantID":0,'s':"dsf"},{"tenantID":1,'s':"dsf"}, {"tenantID":2,'s':"dsf"},{"tenantID":3,'s':"dsf"}, {"tenantID":4,'s':"dsf"},{"tenantID":5,'s':"dsf"}]; var obj = {}; for(var i = 0; i < dataset.length; i++){ if(dataset[i].tenantID == lastLoginTenantId){ //var index = i; obj =dataset[i]; dataset.splice(i,1); // 第i位删除1项 dataset.unshift(obj) } }

怎么把数组中的某一项移动到第一项
文章图片
测试demo.png 是不是很麻烦,哈哈,要是有更好的方法,请email我:zhouminghangqdgcs@163.com
项目中的场景 这里暂时不写了,就是记录一下最后的id,到localStorage里面。

  • localStorage.setItem("LoginUserId_"+loginUserId, id);

    【怎么把数组中的某一项移动到第一项】点击登陆按钮,保存最后的租户id到localStorage
    loginClick = function (tId) { var loginUserId = $("#username").val().trim(); if (self.parent.document.loginType != "popup") { if ($("#p_username").val().indexOf("\"") >= 0) { alert("用户名不能含有非法字符\"!"); return false; } //提交前,增加逻辑判断 toastr.options = { "positionClass": "toast-top-center" }; var userId = $("#username").val(); var password = $("#p_password").val(); if(null==userId || ""==userId.trim()){ toastr.error("请输入登陆账号"); return; } if(null==password || ""==password.trim()){ toastr.error("请输入登陆密码"); return; } //var tenantselect = $("#tenantID"); //var tenantID = tenantselect.val(); var tenantID = tId?tId:""; $("#tenantID").val(tenantID); //检测用户账号密码是否相同 var checkParam = { service: "BC23", method: "checkPWD", eiinfo: '{attr:{"service":"BC23","method":"checkPWD","user":"'+userId+'","password":"'+ password +'"},blocks:{}}' }; var check_status = 0; $.ajax( { type: "POST", async: false, url: CONTEXT_PATH + "/EiService", data: checkParam, dataType: "json", success: function (msg) { var status = msg['status']; check_status = status; if (status<0) { toastr.options = { "positionClass": "toast-top-center" }; if(-98==status){ window.location.href = "https://www.it610.com/article/DispatchAction.do?efFormEname=ES23&userId="+userId; return false; } if(-99==status){ if(null==tenantID || ""==tenantID){ toastr.info(msg['msg']); getTenantList(); $("#tenant-model-box").show(); $("#closeModel").click(function(){ $("#searchTenant").val(""); $("#divSelectLi").empty(); $("#tenant-model-box").hide(); }); var selectIndex = -1; $("#searchTenant").focus(); //$(document).keydown(function(event){ //$(document).keyup(function(event){ $("#searchTenant").keyup(function(event){ var target = event.target; var selectUi = document.getElementById("divSelectLi"); //取得li的元素 var selectList = document.getElementsByClassName("search-li-tenant"); for(var i=0; i 0){ $("#divSelectLi li").removeClass("gr"); $("#divSelectLi li:nth-child(" + (selectIndex + 1) + ")").addClass("gr"); var id = $("#divSelectLi .search-li-tenant .selectTenantIdLi")[selectIndex].innerHTML; var loading = '怎么把数组中的某一项移动到第一项
    文章图片
    正在登录中,请等待...'; $("#divSelectLi li:nth-child(" + (selectIndex + 1) + ")").children(".addLoding").empty().append(loading); localStorage.setItem("LoginUserId_"+loginUserId, id); loginClick(id); }//selectIndex = -1; } break; default: setTimeout(function(){ $("#divSelectLi").empty(); if ($("#divSelectLi li").length == 0) { getTenantList(); } },500); break; } if(selectIndex < 7){ $(".search-result")[0].scrollTop = 0; }else if(selectIndex < $("#divSelectLi li").length){ $(".search-result")[0].scrollTop = (selectIndex-7)*36; }else{ selectIndex = -1; $(".search-result")[0].scrollTop = 0; } if(selectIndex>=0){ $("#divSelectLi li:nth-child("+(selectIndex+1)+")").css("borderLeftColor","#ff9900"); } }); $("#searchTenant").blur(function(){ $("#divSelectLi li").click(function(){ $("#divSelectLi li").removeClass("gr"); var loading = '怎么把数组中的某一项移动到第一项
    文章图片
    正在登录中,请等待...'; $(this).addClass("gr"); var id = $(this).children(".selectTenantIdLi").html(); $(this).children(".addLoding").empty().append(loading); localStorage.setItem("LoginUserId_"+loginUserId, id); loginClick(id); }); }); }else{ check_status = 1; } }else{ toastr.error(msg['msg']); } } }, error: function (xmlR, status, e) { check_status = -1; toastr.error("登陆异常"); } }); if(check_status<0){ return; } $("#p_username").val(userId); document.getElementById('ef-LoginForm').submit(); } else { //$$LOGIN$$:"true" 支持silverlight登录,用于处理sessionvar cookieStr = window.getTopWnd().document.getElementById("COOKIE").value; var jsonEi = "{}"; var reqParams = { service: "EP50", method: "initLoad", eiinfo: jsonEi, $$LOGIN$$: "true", $$keepSession$$: "true", p_username: ef.get("p_username").value, p_password: ef.get("p_password").value, RELOGIN: ef.get("RELOGIN").value, COOKIE: cookieStr }; if ($('#p_captcha').length > 0) {//开启了验证码功能 reqParams = { service: "EP50", method: "initLoad", eiinfo: jsonEi, $$LOGIN$$: "true", $$keepSession$$: "true", p_username: ef.get("p_username").value, p_password: ef.get("p_password").value, p_captcha: ef.get("p_captcha").value, RELOGIN: ef.get("RELOGIN").value, COOKIE: cookieStr }; } $.ajax( { type: "POST", async: false, url: CONTEXT_PATH + "/EiService", //data:"service=" + sService + "&method=" + sMethod + "&eiinfo=" + jsonEi, data: reqParams, dataType: "json", success: function (msg) { ajaxEi = Json2EiInfo.prototype.parseJsonObject(msg); if (ajaxEi.status == "-1") { if (isAvailable(msg.msg)) { $("#loginTip").css("color", "red").text("*" + msg.msg); } else { $("#loginTip").css("color", "red").text("*" + "登录失败,用户名不能为空"); }} else { parent.$.fn.colorbox.close(); var topWnd = getTopWnd(); if (isAvailable(topWnd) && isAvailable(topWnd.lastActivity)) { topWnd.lastActivity = new Date().getTime(); }//self.parent.window.lastActivity = new Date().getTime(); }//用于session恢复.当第一次session失效重登录后,如果当前页面没有刷新而session再次失效,那再页面中保存的保存的sessionId还是原来的值,所以需要更新sessionId var platSessionId = ajaxEi.get("platSessionId"); if (platSessionId != null && platSessionId.trim() != "") window.getTopWnd().document.getElementById("COOKIE").value = https://www.it610.com/article/platSessionId; }, error: function (xmlR, status, e) { //20080806增加 当Ajax调用失败是 将ajaxEi置空(hubing) ajaxEi = null; $("#loginTip").css("color", "red").text("*" + "AJAX请求异常,登录失败!"); } }); } //else }

    从本地localStorage获取该用户,最后的登陆租户id,将最后登陆的放在最前方即可。
    function getTenantList(){ var loginUserId = $("#username").val().trim(); var tName = $("#searchTenant").val().trim()? $("#searchTenant").val().trim():""; var lastLoginTenantId = localStorage.getItem("LoginUserId_"+loginUserId); var param1 = { service: "BC23", method: "getTenantList", eiinfo: '{attr:{"service":"BC23","method":"getTenantList","limit":"-1","offset":"0","showCount":"true","tenantName":"'+tName+'"},blocks:{}}' }; $.ajax( { type: "POST", async: false, url: CONTEXT_PATH + "/EiService", data: param1, dataType: "json", success: function (result) { var resultStatus = result.status; if(resultStatus=='0') { var allCount = result.attr.count; $("#showTenantListCount").html(allCount); var dataset = result.attr.tenants; if(dataset.length == '0'){ varcreateLi =''+ '怎么把数组中的某一项移动到第一项
    文章图片
    '+ '没有查询到符合条件的记录'+ ''; $("#divSelectLi").append(createLi); }if(lastLoginTenantId){ var obj = {}; for(var i = 0; i < dataset.length; i++){ if(dataset[i].tenantID == lastLoginTenantId){ obj =dataset[i]; dataset.splice(i,1); dataset.unshift(obj) } } }for (var i = 0; i < dataset.length; i++) { if ('社会' == dataset[i].tenantGroupType) { color = "#ef8c00"; } if ('企业' == dataset[i].tenantGroupType) { dataset[i].color = "#43a300"; } if ('宝钢' == dataset[i].tenantGroupType) { dataset[i].color = "#0043a3"; } if ('欧冶' == dataset[i].tenantGroupType) { dataset[i].color = "#e60012"; }var createLi = '
  • ' + '' + '' + dataset[i].tenantName + ' ' + '' + dataset[i].tenantID + '' + '' + dataset[i].tenantGroupType + '' + '
  • '; $("#divSelectLi").append(createLi); } } }, error: function (xmlR, status, e) { console.log(e); } }); }

      推荐阅读