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?

JavaScriptで有効な最初の値を検索する関数

Posted at

概要

JavaScriptで、複数の値から最初の有効値を返す関数です。
ここでは有効値の定義を、「null、undefined、NaN、Infinity、-Infinity」を除いたものとしています。

定義

function findFirstValidValue(...values){
    for(let v of values){
        if(typeof v === "number"){
            if(Number.isFinite(v){
               return v; 
            }
            continue;
        }else{
            if(typeof v !== "undefined" && v !== null){
               return v;
            }
            continue;
        }
    }

    return null
}

使用例

const x = findFirstValidValue(null, 1, 2, NaN);
const y = findFirstValidValue(undefined, Infinity, NaN, -Infinity);
console.log("x is " + x + ", y is " + y + ".");

表示

x is 1, y is null.
0
0
3

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?