Javascript check is in array. 2009-06-29 12:21:50

Dùng cho số và chuỗi thôi.

var arr = [2, 3, 4 , 5];
var num = 4;
if (arr.join(" ").indexOf(num) < 0) {
alert("not in");
} else {
alert("ok");
}

cách check này sẽ nhanh hơn khi viết theo kiểu dùng vòng lặp (for, while) như bình thường nhưng cách này không kiểm tra được với dữ liệu kiểu object.

Tra loi 12 comment(s) uoon 2009-06-29 12:21:50

TG 2009-06-29 01:04:55

Cách này sẽ không chính xác nếu mảng trong mảng có các giá trị 14,24,.....

Tra loi

uoon 2009-06-29 04:13:03

ừ hén, quên mất :D thax TG

Tra loi

Về Đâu 2009-06-30 12:03:18

function in_array(string, array)  
{  
    for (i = 0; i < array.length; i++)  
    {  
       if(array[i] == string)  
       {  
          return true;  
       }  
    }  
return false;  
}  

Tra loi

choncon 2009-07-01 11:14:07

Ăn nhau là ở chỗ số vòng lặp để tăng tốc :

function in_array(value, array){  
    for (i = 0; i < array.length / 2 ; i++)
       //tiết kiệm 50% tốc độ  
       if(array[2*i] === value || ( i > 0 && array[2*i - 1] === value ))
          return true;  
    return false;  
}  

Tra loi

Ken Phan 2009-07-01 11:46:25

hàm hay thật ^^ mà ăn nhau ở chỗ phải kiểm tra array có phải array ko ?
function in_array(value, array){
    if(!is_array(array)) return false;
    for (i = 0; i < array.length / 2 ; i++)
       //tiết kiệm 50% tốc độ  
       if(array[2*i] === value || ( i > 0 && array[2*i - 1] === value ))
          return true;  
    return false;  
}
hàm is_array()
function is_array( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true  in this function (except for objects which inherit properties, being thus used as objects),
    // %        note 1: unless you do ini_set('phpjs.objectsAsArrays', true), in which case only genuine JavaScript arrays
    // %        note 1: will return true
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 3: true
    // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
    // *     returns 4: false

    var key = '';
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if(!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    if (!mixed_var) {
        return false;
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    if (typeof mixed_var === 'object') {

        if (this.php_js.ini['phpjs.objectsAsArrays'] &&  // Strict checking for being a JavaScript array (only check this way if call ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays)
            (
            (this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase &&
                    this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase() === 'off') ||
                parseInt(this.php_js.ini['phpjs.objectsAsArrays'].local_value, 10) === 0)
            ) {
            return mixed_var.hasOwnProperty('length') && // Not non-enumerable because of being on parent class
                            !mixed_var.propertyIsEnumerable('length') && // Since is own property, if not enumerable, it must be a built-in function
                                getFuncName(mixed_var.constructor) !== 'String'; // exclude String()
        }

        if (mixed_var.hasOwnProperty) {
            for (key in mixed_var) {
                // Checks whether the object has the specified property
                // if not, we figure it's not an object in the sense of a php-associative-array.
                if (false === mixed_var.hasOwnProperty(key)) {
                    return false;
                }
            }
        }

        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        return true;
    }

    return false;
}

Tra loi

choncon 2009-07-01 12:06:16

Sao rối rắm thế ,is_array thfi chỉ cần:

function isArray(a){
return a && a.constructor === Array;
}

Tra loi

uoon 2009-07-01 12:28:17

Nói chung là đang tìm cách kiểm tra inArray trong js sao cho ngắn ngọn :). Thật buồn là vẫn chưa nghĩ ra :(
@choncon: cái của đồng chí áp dụng thuật toán tìm kiếm rất hay ^^ biết chia 2 phần cho nhanh sao không chia luôn thành 2^n phần :p

Nhưng nếu dùng for length nên chú ý trường hợp này:

var arr = [];
arr[4294967295] = 1;
và arr["a"] = "b";


Tra loi

Ken Phan 2009-07-01 01:05:23

ý àh :D hàm của tớ lấy từ php to js muz` ... is_array() trong js cho ae dễ hĩu :">
var arr = [];
arr[4294967295] = 1;
và arr["a"] = "b";
:D kiểu này thì cách của choncon pó tay lalala

Tra loi

choncon 2009-07-01 06:45:27

@unoon: giải thuật đó ko cải tiến về số phép tính của CPU nhưng có í nghĩa về mặt thực tế.
@kenphan : với kiểu đó thì nó thành object rồi ,lúc đó lại phải tạo hàm makeArray hoặc for( x in array)

Tra loi

uoon 2009-07-02 12:41:04


Kết thúc vụ này với cách check dùng for in truyền thống.
Anh em dùng firefox có thể test đoạn code này:
<?php
var arr = [2, 3, 4, 34, 44];
arr[1000] = "hai";
var
num = 34;

function
isIn(ele, arr) {
var
gel = "-" + new Date().getTime() + ";";
return ((
arr.join(gel)+gel).indexOf(ele+gel) > -1);
}

function
In(ele, arr) {
for (var
i in arr) {
if (!Array.
prototype[i] && ele == arr[i] ) {
return
true;
}
}
return
false;
}

var
start = new Date().getTime();

for (var
i = 0; i < 5000; i ++) {
isIn(num, arr);
}

var
next = new Date().getTime();

for (var
i = 0; i < 5000; i ++) {
In(num, arr);
}

var
end = new Date().getTime();

console.log(next - start);
console.log(end - next);
?>
Thế nhá, anh em khi làm việc với array nên dùng for...in giống hàm In ở trên.

Tra loi

Ken Phan 2009-07-02 11:40:11

acx _ _! trùi ui ... code uoon oách thật ... :D nhìn hem hĩu gì lun ... js mình gà thật ! mỗi sài đc jquery ! thế bác nào đọ jquery với tui hem :D haha

Tra loi

cóc 2009-07-03 08:07:45

acx _ _! trùi ui ... code uoon oách thật ... :D nhìn hem hĩu gì lun ... js mình gà thật ! mỗi sài đc jquery ! thế bác nào đọ jquery với tui hem :D haha

Đúng òi, em zai Ken là trùm Jquery rồi, bằng chứng này:
http://goldengate.com.vn/clientscript/js/jquery.slinav.js
http://goldengate.com.vn/clientscript/js/jquery.validate.js
http://goldengate.com.vn/clientscript/js/jquery.tooltip.js

Author Ken Phan

Tra loi

Y kien