我看到了这个问题,但是没有看到JavaScript特定的示例。string.EmptyJavaScript中是否有一个简单的可用工具,还是仅用于检查的情况""?
我看到了这个问题,但是没有看到JavaScript特定的示例。string.EmptyJavaScript中是否有一个简单的可用工具,还是仅用于检查的情况""?
Answers:
如果您只想检查是否有任何价值,可以
if (strValue) {
//do something
}
如果您需要专门为在空空字符串检查,我想核对""是你最好的选择,使用的===运营商(让你知道这是,事实上,一个字符串你比较反对)。
if (strValue === "") {
//...
}
=== ''vs .length并没有显示任何明显的改进(并且.length只有在可以假设您有字符串的情况下才使用)
为了检查字符串是否为空,空或未定义,我使用:
function isEmpty(str) {
return (!str || 0 === str.length);
}
为了检查字符串是否为空,空或未定义,我使用:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
用于检查字符串是否为空白或仅包含空格:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
if (variable == constant value),如果您忘记了“ =”,则将常量值分配给变量而不是进行测试。该代码仍然可以使用,因为您可以在if中分配变量。因此,写此条件的更安全方法是反转常数值和变量。这样,当您测试代码时,您会看到一个错误(分配中的左手无效)。您还可以使用JSHint之类的东西来禁止条件分配,并在编写条件时发出警告。
/^\s*$/.test(str)很难理解的耻辱-也许使用更简单的代码或正则表达式删除空格会更好?看到stackoverflow.com/questions/6623231/...也stackoverflow.com/questions/10800355/...
if blue is the sky。请参阅dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html
先前的所有答案都不错,但这会更好。使用!!(不是)运算符。
if(!!str){
// Some code here
}
或使用类型转换:
if(Boolean(str)){
// Code here
}
两者执行相同的功能。将变量类型转换为布尔值,其中str是变量。
它返回false了null,undefined,0,000,"",false。
返回true字符串“ 0”和空格“”。
if(str)和if(!!str)?
var any = (!!str1 && !!str2 && !!str3)处理其中是否存在数字
!!str.trim()确保该字符串不是仅由空格组成。
Boolean(str)而是更具可读性和更少的“ wtfish”。
您可以得到的最接近的结果str.Empty(以str为字符串为前提)是:
if (!str.length) { ...
str.Empty。
如果您需要确保字符串不只是一堆空白(我假设这是用于表单验证),则需要对这些空格进行替换。
if(str.replace(/\s/g,"") == ""){
}
if(str.match(/\S/g)){}
str.match(/\S/)
var trimLeft = /^\s+/, trimRight = /\s+$/;
我用:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof(e) == "undefined":
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
typeof在switch没有为我工作。我添加了一个if (typeof e == "undefined")测试,并且可以正常工作。为什么?
case undefined:代替使用case typeof(e) == "undefined":吗?
您可以使用lodash:_.isEmpty(value)。
它涵盖了很多类似的情况下{},'',null,undefined,等。
但它总是返回true的Number类型的JavaScript的基本数据类型一样_.isEmpty(10)或者_.isEmpty(Number.MAX_VALUE)两者的回报true。
_.isEmpty(" "); // => false
" "不为空。_.isEmpty("");返回true。
功能:
function is_empty(x)
{
return (
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
PS:在JavaScript中,请勿在之后使用换行符return;
if语句中是没有意义的。
尝试:
if (str && str.trim().length) {
//...
}
str.trim().lengthstr.trim()根据我自己的测试结果,速度会比快1%。
if (!str) { ... }
我不会太担心最有效的方法。使用最清楚您意图的内容。对我来说通常是strVar == ""。
根据康斯坦丁(Constantin)的评论,如果strVar最终可以包含整数0,那么这确实是意图澄清的情况之一。
很多答案,还有很多不同的可能性!
毫无疑问,快速简便的实现是: if (!str.length) {...}
但是,还有许多其他示例可用。为此,最好的功能方法是:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
{
return true;
}
else
{
return false;
}
}
我知道有点过分了。
str.length === 0对于没有形式参数的任何函数,返回true。
我在macOS v10.13.6(High Sierra)上针对18种选定的解决方案进行了测试。解决方案的工作方式略有不同(针对极端情况下的输入数据),下面的代码段对此进行了介绍。
结论
!str,适用于所有浏览器(A,B,C,G,I,J)=====lengthtest,replace)的解决方案,并且charAt对于所有浏览器(H,L,M,P)都是最慢的在下面的代码段中,我将使用不同的输入参数来比较选择的18种方法的结果
"" "a" " "-空字符串,带字母的字符串和带空格的字符串[] {} f-数组,对象和函数0 1 NaN Infinity -数字true false -布尔值null undefined并非所有测试方法都支持所有输入情况。
然后,对于所有方法,我都会str = ""针对浏览器Chrome v78.0.0,Safari v13.0.4和Firefox v71.0.0 执行速度测试用例-您可以在此处在计算机上运行测试
我通常用这样的东西
if (!str.length) {
// Do something
}
typeof variable != "undefined"在检查是否为空之前进行检查。
我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
要测试其无效性,可以执行以下操作:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
它适用于空字符串和空字符串,并且所有字符串均可访问。另外,它可以扩展为包含其他JavaScript空字符或空格字符(即,不间断空格,字节顺序标记,行/段落分隔符等)。
同时,我们可以使用一个函数来检查所有“空”,例如null,undefined,'',',{},[]。所以我只是写了这个。
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
用例和结果。
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
到目前为止,还没有像string.empty这样的直接方法来检查字符串是否为空。但是在您的代码中,您可以使用包装检查是否为空字符串,例如:
// considering the variable in which your string is saved is named str.
if (str && str.length>0) {
// Your code here which you want to run if the string is not empty.
}
使用此方法,您还可以确保字符串也未定义或为null。记住,未定义,null和empty是三件事。
let rand = ()=>Math.random(),然后rand && rand.length > 0)返回false,但显然fn不是“空”。即,对于没有格式参数的任何函数,它返回false。
Math.random()返回数字而不是字符串。这个答案是关于字符串的。;-)
所有这些答案都很好。
但是我不能确定变量是一个字符串,不只包含空格(这对我很重要),并且可以包含“ 0”(字符串)。
我的版本:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
jsfiddle示例。
empty(0)而empty(7)应返回相同的值。
empty("0")必须返回false(因为它不是一个空字符串),但empty(0)必须返回,true因为它为空:)
empty在这种情况下,这是一个令人误解的名称。
empty很好。在php docs中,空函数:和此函数Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.之间的区别PHP-该字符串'0'不会被标识为空。
empty是一个不准确且具有误导性的名称。有趣的是,PHP也具有一个命名错误的empty函数,但是PHP的失败与JavaScript没有任何关系。
我在这里没有找到好的答案(至少不是适合我的答案)
所以我决定回答自己:
value === undefined || value === null || value === "";
您需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后可以检查它是否等于null或等于空字符串。
你不能拥有!或仅if(value)当您选中0该选项后才会给出错误答案(0为错误)。
话虽如此,将其包装为以下方法:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS .:您不需要检查typeof,因为它甚至在进入方法之前都会爆炸并抛出。
尝试这个
str.value.length == 0
"".value.length会导致错误。应该是str.length === 0
TypeErrorIf如果str等于undefined或null
您可以轻松地将它添加到本地字符串对象的JavaScript又一遍地重复使用......
一些简单的像下面的代码可以,如果你要检查你做的工作''空字符串:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
否则,如果您想同时检查''空字符串和' '空格,则只需添加即可trim(),例如下面的代码:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
您可以这样称呼:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
!(!!this.length)不仅是!this(或!this.trim()为第二种选择)有什么好处?零长度的字符串已经很虚假,括号是多余的,对它进行三次否定与否定一次完全相同。
我对将非字符串和非空/空值传递给测试器函数时会发生的情况进行了一些研究。众所周知,(0 ==“”)在JavaScript中为true,但是由于0是一个值且不是空或null,因此您可能需要对其进行测试。
以下两个函数仅对未定义,null,空白/空白值返回true,对其他所有值(例如数字,布尔值,对象,表达式等)返回false。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
存在更复杂的示例,但是这些示例很简单并且给出了一致的结果。无需测试未定义,因为它已包含在(value == null)检查中。您也可以通过将C#行为添加到String中来模拟C#行为,如下所示:
String.IsNullOrEmpty = function (value) { ... }
您不希望将其放在Strings原型中,因为如果String-class的实例为null,它将出错:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
我使用以下值数组进行了测试。如果有疑问,可以循环遍历以测试您的功能。
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
为避免在testis undefined或时发生运行时错误,需要进行类型检查null。