document.cookie = 'name='+'username'; document.cookie = 'value='+'value1'; var cookarr = document.cookie.replace(/s/g,"").split(';');//将cookie的空格全部替换掉,不然会出现空格,使结果无法判断 var havcome = false; for (var i=0;i<cookarr.length;i++){ var str = cookarr[i].split('='); if(str[0]=='dateam') { havcome = true; break } } console.log(document.cookie); console.log(havcome); var date = new Date(); var day = date.getTime(); console.log(day); var newday = new Date(day + 7*24*60*60*1000);//设置过期时间,这里设置为七天之后; var oldday = new Date(day -1);//设置删除时间,只要过期时间在设置时间之前,就可以将cookie删除; console.log(newday.toUTCString()); if (!havcome){ document.cookie = 'dateam'+'='+'haha'+';expires='+newday.toUTCString(); alert('欢迎你第一次来'); } document.cookie = 'dateam'+'='+'haha'+';expires='+oldday.toUTCString();//将过期时间设置为已经过去的 1 ms,则可以立即删除dateamcookie