JavaScript切换案例:无论如何要强制将元素写出顺序? [英] JavaScript switch case: anyway to force the order of the elements as they are written out?

查看:91
本文介绍了JavaScript切换案例:无论如何要强制将元素写出顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将结果返回到div侧栏中的Google Mapping应用程序中.结果是属于客户希望按特定顺序退回的类别的企业名称.不幸的是,这不是直接的alpha排序.例如,一个类别以F开头,第二个类别以C开头,最后三个类别是A.

I've got results being returned to a Google Mapping application in the div sidebar. The results are names of businesses that belong to categories that the client wants returned in a certain order. And unfortunately it's not a straight alpha sort. So one category begins with F and the second one with a C and the last three are A's, for example.

所以我需要我的开关,它可以工作,但是自然会坚持以alpha排序的值(因为它们是从数据库中返回的)删除按顺序排列的值,因为这就是它们遇到它们的方式.进行设置的最佳方法是什么,这样我就可以按照客户要求的任意顺序来获取我的首选类别及其关联的公司名称?

So I need my switch, which works, but naturally insists on dropping the values in alpha sorted (as they are returned from the DB that way) order as that's how it encounters them. What's the best way to set this up so I can grab my preferred categories with their associated company names in the arbitrary order the client has asked for?

谢谢!

推荐答案

因此,此处给出的答案中缺少的步骤是如何实现地图以及如何实现JS代码段.无论如何,我最终不得不作为一个单独的问题来问,最后得到一个很好的可行示例作为答案.

So the missing step in the answer given here was HOW the map would be implemented and HOW the JS snippet could be implemented. Anyway, I ended up having to ask that as a separate question and finally got a nice working example for an answer.

Russ写道:

Russ wrote:

给出的代码很可能是 使用jQuery JavaScript库 具有一些有用的功能,例如 map()用于处理数组.

The code given looks most likely to be using the jQuery JavaScript library that has some useful functions such as map() for manipulating arrays.

如果我们回到最初的问题, 您需要订购类别列表 根据客户的偏好. 让我们创建一个对象常量 映射顺序

If we go back to the original problem, you need to order a list of categories based on the client's preference. Let's create a an object literal to map the ordering

var map = {
     F : 5,
     C : 3,
     A1 : 1,
     A2 : 4,
     A3 : 2
 }

我们可以使用此映射对数组进行排序 使用排序方法

We can use this map to order the array using the sort method

 var array = ['F', 'C', 'A1', 'A2', 'A3'];

 array.sort(function(a,b) {
     return map[a] - map[b];
 });
 This returns us ["A1", "A3", "C", "A2", "F"]

无论如何,我想确保将来有人在搜索此问题或现在正在关注此问题的任何人都将此内容包括在此线程中.感谢大家的投入!

Anyway, I wanted to make sure this was included on this thread for anyone searching for this issue in the future or anyone following along right now. Thanks for everyone's input!

这篇关于JavaScript切换案例:无论如何要强制将元素写出顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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