js 一些操作

1.判断字符串是否包含另一个字符串 参考Js判断一个字符串是否包含一个子串

用js的indexOf()方法,该方法返回值由三种可能 -1,0,1 。如果是-1 说明字符串不包含。

<script>
	function test() {

		var str1 = "hello world";
		var str2 = "chello";

		console.log(str1.indexOf("llo")); //2 包含
		console.log(str1.indexOf("he"));  //0 包含
		console.log(str1.indexOf("11"));  //-1 不包含
		//判断包含
		if (str1.indexOf(str2) >= 0) {
			console.log("str1 contained str2")
		}
	}
</script>

2.  typeof() 方法    返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"

<script>
	function testTypeof() {

		//typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined" 
		var number1 = 2;
		console.log(typeof (number1));

		var str = "hello";
		console.log(typeof (str));

		var isTrue = true;
		console.log(typeof (isTrue));

	}
</script>

3.js判断null undefined 与NaN方法  参考 JS中判断null、undefined与NaN的方法

<script>

	function test() {

		var tmp = undefined;
		if (typeof (tmp) == "undefined") {
			console.log("undefined");
		}

		var tmp = null;
		if (!tmp) {
			console.log("null");
		}

	}
</script>

4.js 操作json对象 :添加,修改,删除,for循环等操作   可以用 . 或者 []  来访问操作 json对象 但是for循环里只能用[] 不能用.

参考 JSON 对象    js给json对象添加、删除、修改属性

<script>
	function testJson() {

		//定义json对象
		var jsonObj = {
			"name" : "zhangsa",
			"age" : 22
		};

		//添加属性
		jsonObj.sex = "female";
		//修改属性
		jsonObj.age = 24;
		//删除属性
		delete jsonObj.name;
		
		//for 循环json对象, x 是json对象的属性(key) , 获取json对象的属性值(value)是只能用[] 不能用 .
		for (x in jsonObj) {
			console.log("x", x); //key
			console.log("jsonObj.x", jsonObj[x]); //value
		}

	}
</script>

 

posted on 2020-02-26 11:33  dreamstar  阅读(54)  评论(0编辑  收藏  举报