0

我正在寻找与 php 完全相同的 Javascript 等价物:

$tags = preg_split('/+/', $_GET['q'], NULL, PREG_SPLIT_NO_EMPTY);
$p = array_unique(array_map('strtolower', $tags));
sort($p);

快完成了

var queryString = decodeURIComponent(location.search.substring(1)).toLowerCase(); 
var key = queryString.split('&')[0].split('=');
if (key.length > 1){ //q should be the only query key
    var tags = key[1].split(/\+/g);
    // make tags values unique, non-empty and ordered alphabetically
}

但我正在寻找使标签值唯一、非空且按字母顺序排列的 3 件事,这在 php 中很容易完成,我希望在 JavaScript 中有这样的解决方案。

4

2 回答 2

3

你可以在 phpjs 项目中找到它:

代码:

split: (explode依赖)

function split (delimiter, string) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: explode
    // *     example 1: split(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    return this.explode(delimiter, string);
}

array_unique

function array_unique (inputArr) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: The second argument, sort_flags is not implemented;
    // %          note 1: also should be sorted (asort?) first according to docs
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {a: 'green', 0: 'red', 1: 'blue'}
    var key = '',
        tmp_arr2 = {},
        val = '';

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty(fkey)) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };

    for (key in inputArr) {
        if (inputArr.hasOwnProperty(key)) {
            val = inputArr[key];
            if (false === __array_search(val, tmp_arr2)) {
                tmp_arr2[key] = val;
            }
        }
    }

    return tmp_arr2;
}
于 2012-06-09T11:45:56.240 回答
0

因为我最终在这里进行了搜索,array_unique js equivalent所以我认为值得一提的是,在 ES6 中你可以

var unique = (value, index, array) => array.indexOf(value) === index;

[1,1,1,2,3].filter(unique);

或在 1 行

[1,1,1,2,3].filter((v, i, a) => a.indexOf(v) === i)
于 2017-04-06T11:51:08.983 回答