0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

typescript(javascript)でarrayかhashかを判定する

Last updated at Posted at 2017-10-19

ネットで拾ってきたコードをtypescript用に修正したメモ

  • hashはピンポイントで特定できない
  • typeofを地道に使う
judgeArrOrHash(obj) {
    if((typeof obj) === 'object'){
      if(obj.length != undefined){
        console.log('array');
        return 'array'
      } else{
        for(let t in obj) {
          if(obj[t] != undefined) {
            console.log('hash');
            return 'hash'
          }
          else {
            console.log('object');
            return 'object';
          }
        }
      }
    } else {
      console.log('not array nor hash');
      return (typeof obj)
    };
  }

使ってみる

  let arrdata = [1,2,3];
  let hashdadta = { key1: 2, key2: 3};
    
  this.judgeArrOrHash(arrdata);
  // => array
  this.judgeArrOrHash(hashdadta);
  // => hash
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?