zoukankan      html  css  js  c++  java
  • js判断数组,对象是否存在某一未知元素

    1.对象   

    1 var obj = {
    2     aa:'1111',
    3     bb:'2222',
    4     cc: '3333'
    5 };
    6 var str='aa';
    7 if(str in obj){
    8     console.log(obj[str]);
    9 }

    但是对于obj内的原型对象,也会查找到:

    1 var obj = {
    2     aa:'1111',
    3     bb:'2222',
    4     cc: '3333'
    5 };
    6 var str='toString';
    7 if(str in obj){
    8     console.log(obj[str]);
    9 }

    所以,使用hasOwnProperty()更准确:

     1 var obj = {
     2     aa: '1111',
     3     bb: '2222',
     4     cc: '3333'
     5 };
     6 var str = 'aa';
     7 if (obj.hasOwnProperty(str)) {
     8     console.log(111);
     9 }else{
    10     console.log(222);
    11 }

    2.数组

    如何判断数组内是存在某一元素?主流,或者大部分都会想到循环遍历,其实不循环也可以,通过数组转换查找字符串:

    1 var test = ['a', 3455, -1];
    2 
    3 function isInArray(arr, val) {
    4     var testStr = arr.join(',');
    5     return testStr.indexOf(val) != -1
    6 };
    7 alert(isInArray(test, 'a'));

    通过While循环:

    Array.prototype.contains = function(obj) {
        var len = this.length;
        while (len--) {
            if (this[len] === obj) {
                return true
            }
        }
        return false;
    };

    for循环:

    Array.prototype.contains = function(obj) {
        var len = this.length;
        for (var i = 0; i < len; i++) {
            if (this[i] === obj) {
                return true
            }
        }
        return false;
    }
  • 相关阅读:
    自定义控件-控件关联
    DELPHI INSERT INTO 语句的语法错误 解决方法
    Delphi控件开发
    Delphi控件复合控件
    vcl学习备忘网址
    Delphi单元文件Unit详解
    aowner , nil 和 self 的区别
    Delphi 自定义事件的例子
    PHP中Heredoc
    What is HTTP_USER_AGENT?
  • 原文地址:https://www.cnblogs.com/peng14/p/4848672.html
Copyright © 2011-2022 走看看