Does Javascript or jQuery have sometime like the "in" statement in Python?
"a" in "dea" -> True
Googling for the word in is hopeless :(
It does have an in operator but is restricted to object keys only:
var object = {
a: "foo",
b: "bar"
};
// print ab
for (var key in object) {
print(key);
}
And you may also use it for checks like this one:
if ("a" in object) {
print("Object has a property named a");
}
For string checking though you need to use the indexOf() method:
if ("abc".indexOf("a") > -1) {
print("Exists");
}
you would need to use indexOf
e.g
"dea".indexOf("a"); will return 2
If its not in the item then it will return -1
I think thats what you are after.
Sounds like you need regular expressions!
if ("dea".match(/a/))
{
return true;
}
How about indexOf?
With the indexOf function, you can extend the String like such:
String.prototype.in = function (exp) {
return exp.indexOf(this) >= 0;
}
if ("ab".in("abcde")) { //true
}
Related
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there an easier way to determine if a variable is equal to a range of values, such as:
if x === 5 || 6
rather than something obtuse like:
if x === 5 || x === 6
?
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1 is returned then the variable doesn't exist in the array.
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
if ([5,6,7,8].indexOf(x) > -1) {
}
Yes. You can use your own function. This example uses .some:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
This is what I've decided to use:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
You would use it like this:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
it works in IE < 9;
it reads naturally from left to right;
you can feed it arrays or separate values.
If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
no, there might be a few tricks that are case specific but in general i write code like this:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
Easiest way I know :
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.
I want to create a function which can take n1, n2, n... , n = number of params.
I'm aware that there is such thing as using arguments[0] object to select parameters. Would it be possible to loop through all passed parameters and check that their value ! = ""
function test () {
loop through arguments[] object
IF arguments[index] == "" return false
};
test("ok","", "no"); would return false
test("ok"); would return true
The objective is that the function works even if there isn't a set amount of parameters.
Javascript and jQuery answers both welcome.
PS: If it is possible, are there limitations ? Possible problems.
Short ECMAScript5 solution using Array.prototype.slice() and Array.prototype.some() functions:
function checkFilling() {
return !Array.prototype.slice.call(arguments).some(function (arg) {
return arg === "";
});
}
console.log(checkFilling("ok","", "no"));
console.log(checkFilling("ok"));
Alternative ECMAScript6 approach using Array.from() function(to create a new array from an array-like arguments object):
function checkFilling() {
return !Array.from(arguments).some(arg => arg === "");
}
console.log(checkFilling("ok","", "no"));
console.log(checkFilling("ok"));
Answering the question in the spirit it was asked with code that works in all browsers and is readable and understandable by beginners too
function test() {
for (var i=0,n=arguments.length;i<n; i++) {
// return false if any argument is strictly equal to the empty string
if (arguments[i]==="") return false;
}
return true;
}
// Tests
console.log(test(""),false)
console.log(test("1"),true)
console.log(test(1),true)
console.log(test("1",""),false)
console.log(test("1","2"),true)
I'm creating a JSON object like
tags = {"jon":["beef","pork"],"jane":["chicken","lamb"]};
which was generated using php from an array like
$arr = array(
'jon' => array('beef', 'pork'),
'jane' => array('chicken', 'lamb')
);
$tags = json_encode($arr);
And I want to check if something is in one or the other. None of these seem to work, but something like
if('lamb' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
writes NO to the console
if('foo' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes NO to the console
so looking at
typeof(tags.jane);
it shows it's an "object" but
console.log(tags);
shows the following:
Object
jane: Array[2]
0: "chicken"
1: "lamb"
length: 2
__proto__: Array[0]
jon: Array[2]
0: "beef"
1: "pork"
length: 2
__proto__: Array[0]
__proto__: Object
so i thought maybe tags.jane may actually be an array and tried
if($.inArray('lamb', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
which writes YES to the console but
if($.inArray('foo', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes YES to the console.
Am I incorrectly building the JSON Object? Not targeting the value(s) properly? Any advice is greatly appreciated. If this would be easier as an array instead of an object, I have full control to change it. I'm just a bit stumped at how I should treat this.
jQuery.inArray returns -1 when element is not found. That's true value from the POV of Javascript. Try this:
if($.inArray('foo', tags.jane) != -1) {
Your second set of answers are the way you should go. However, $.inArray returns an index, not a boolean. Any non-zero integer is true, which means when foo is not found, it returns -1 which evaluates to true and prints YES.
Similarly, $.inArray('chicken', tags.jane) would return 0 and cast to false, which is also not the answer you want.
Instead, use $.inArray('foo', tags.jane) !== -1 as your condition.
tags.name will give you the array for that person. So $.inArray("chicken",tags.jane) would see if "chicken" is in jane's tags array. If it's not, you'd get -1, otherwise you'd it's position in the array (using your example, this would return zero, the first array element).
You're using the keyword in for the wrong reason.
The statement ( prop 'in' obj ) checks to see if the object(associated array) has a property with the value of prop.
Since you're using the 'in' keyword on an array, then false is going to be returned because tags.jane is an array with indexes and not an associated array with properties.
If you want to know was values are in the array then loop through and compare.
If you want to use the 'in' keyword then convert your array to an object like so.
tags = {};
// old code
tags.jane = ['lamb', 'food'];
console.log(('lamb' in tags.jane) === false )
// new code
tags.jane = {
'lamb':1,
'food':1
}
console.log(('lamb' in tags.jane) === true )
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
you can not use
if('foo' in tags.jane))
it should be used as
if (1 in tags.jane)
if you want to check 'foo' is in tags.jane, try this
var inIt = (function() {
var inIt = false;
tags.jane.forEach(function(item) {
inIt = inIt || 'foo' == item;
});
return inIt;
})();
Does JavaScript have a convenient way to test if a variable matches one of many values?
This is my code,
function Start()
{
if(number==(0||3||6||8||9||11||13||14||15||18||19||22||23||25||27||28||31||34||43||46||47||49||54||58||59||62||63||68||71||74||75))
{
FirstFunction();
}
if(number==(1||4||5||7||12||16||17||20||21||26||29||32||33||42||45||48||50||51||53||55||56||57||60||61||64||65||67||69||70||73||76))
{
SecondFunction();
}
}
as you can see, I tried to use the "or" operator to check if number equals ANY of the listed. this, unfortunately, did not work. I know I can just code:
if(number==0||number==3||number==6....)
I think there should be an alternative to that, is there?
Thank you in advance.
You should insert all your elements in an array and use arr.indexOf(element)
It will return -1 if the element doesn't exist which you can use for your if logic
This is better than having lot of if statements
var x = new Array(1,7,15,18);
if ( x.indexOf(31) != -1 )
{
// Add your logic here
}
You can write something like this, which looks a bit nicer:
This Array prototype function will allow you check if an element exists in a JS array:
Array.prototype.exists = function (x) {
for (var i = 0; i < this.length; i++) {
if (this[i] == x) return true;
}
return false;
}
Then:
function Start()
{
var values1 =[0,3,6,8,9,11,13,14,15,18,19,22,23,25,27,28,31,34,43,46,47,49,54,58,59,62,63,68,71,74,75];
var values2 = [1,4,5,7,12,16,17,20,21,26,29,32,33,42,45,48,50,51,53,55,56,57,60,61,64,65,67,69,70,73,76];
if( values1.exists(number) )
{
FirstFunction();
} else if ( values2.exists(number) )
{
SecondFunction();
}
}
The array techniques already mentioned are good, e.g., [0, 3, 6, 8].indexOf(number) != -1, but note that not all browsers support .indexOf() on arrays (think older IE). If you have a look at the MDN page on .indexOf() you'll see they've provided an implementation of .indexOf() that you can add to the Array.prototype if it doesn't already exist.
But here's a non-array method that will work in older browsers at least as far back as IE6 without needing to add your own functions or modify the prototype of any built-in objects:
if (/^(0|3|6|8|9|11)$/.test(number)) {
// matched, so do something
}
The regex .text() method is expecting a string, but if you give it a number it'll cope.
I'd probably still recommend the array method, but it can't hurt to have another option.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: string contains
Jquery: How to see if string contains substring
In ASP .NET C# I use:
string aa = "aa bb";
if (aa.Contains("aa"))
{
//Some task
}
I want to same thing in client side means in JQuery. Something like below:
var aa = "aa bb";
if(aa. -----want help here){
}
Is there any method to do this?
Use the String.indexOf() MDN Docs method
if( aa.indexOf('aa') != -1 ){
// do whatever
}
Update
Since ES6, there is a String.includes() MDN Docs so you can do
if( aa.includes('aa') ){
// do whatever
}
You don't need jQuery for this. It can be achieved with simple pure JavaScript:
var aa = "aa bb";
if(aa.indexOf("aa") >= 0){
//some task
}
The method indexOf will return the first index of the given substring in the string, or -1 if such substring does not exist.
C#'s implementation of .Contains is actually a wrapper on it's implementation of .IndexOf. Therefore you can create your own .Contains function in javascript like this:
String.prototype.Contains = function (s) {
return this.indexOf(s) != -1;
}
You can use a regular expression for more complex scenarios, or indexOf for simple ones.
if (aa.match(/a(b|c)a/)) {
}
or
if (aa.indexOf('aa') >= 0) {
}
In Javascript you use indexOf for that.
var aa = "aa bb";
if(aa.indexOf('aa') != -1)
{
}
But remember that indexOf is case sensitive.
you can create your own contains method using prototype that
can, if you want, handle that.
String.prototype.contains = function(value, ignorecase) {
if (ignorecase) {
return (this.toLowerCase().indexOf(value.toString().toLowerCase()) != -1);
}
else {
return this.indexOf(value) != -1;
}
};
alert("aa bb".contains("aa"))
Source: 'contains' method in javascript, extend the String prototype and add your own methods.
Since Java 5, contains() also exists and can be used the same way.